//
//  FeedBackViewController.m
//  CMVRFForIOS
//
//  Created by HailongHan on 15/4/19.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "FeedBackViewController.h"
#import <TPKeyboardAvoidingTableView.h>
#import "DefaultStyleTableViewCell.h"
#import "UserProfileData.h"
#import "SuggestionDataResp.h"
#import <MBProgressHUD.h>
#import "PublishNoticeViewController.h"
#import "NoticeViewController.h"
#import "NoticeTableViewCell.h"
#import "MJRefresh.h"

@interface FeedBackViewController () {
    MBProgressHUD *HUD;
    NSUInteger beginIndex;
    NSUInteger endIndex;
    NSUInteger approvedBegin;
    NSUInteger approvedEnd;
}

/**
 *  切换button
 */
@property (strong, nonatomic) UISegmentedControl *segmentControl;

@property (nonatomic,strong) UISearchBar *productSearchBar;
@property (nonatomic,strong) TPKeyboardAvoidingTableView *tableView;
@property (nonatomic,retain) NSMutableArray *dataSourceToMe;
@property (nonatomic,retain) NSMutableArray *dataSourceForMe;
@property (nonatomic,copy) NSString *searchStr;


@end

@implementation FeedBackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self loadData];
}

#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"意见反馈";
    
    //适配iOS7uinavigationbar遮挡tableView的问题
    if(IS_IOS7){
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    //自定义完成选择按钮
    UIBarButtonItem *saveBtn = [[UIBarButtonItem alloc] initWithTitle:@"提意见" style:UIBarButtonItemStyleDone target:self action:@selector(addOneSuggestion)];
    self.navigationItem.rightBarButtonItem = saveBtn;
    
    self.segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"下属意见", @"自提意见"]];
    self.navigationItem.titleView = self.segmentControl;
    [self.segmentControl setWidth:80.0 forSegmentAtIndex:1];//设置指定索引选项的宽度
    [self.segmentControl setWidth:80.0 forSegmentAtIndex:0];//设置指定索引选项的宽度
    
    [self.segmentControl addTarget:self action:@selector(switchView) forControlEvents:UIControlEventValueChanged];
    
    //初始显示下属意见
    [self.segmentControl setSelectedSegmentIndex:0];
    
    self.tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:[UIView frameWithOutNavTab] style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self refreshData];
    }];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    
    [self.view addSubview:self.tableView];
}


#pragma mark - 数据处理
- (void)initData {
    beginIndex = 0;
    endIndex = LIST_PAGE_ITEM_COUNTS - 1;
    approvedBegin = 0;
    approvedEnd = LIST_PAGE_ITEM_COUNTS - 1;
    self.dataSourceToMe = [NSMutableArray new];
    self.dataSourceForMe = [NSMutableArray new];
}

- (void)loadData {
    [self loadALLSuggestion:beginIndex andEnd:endIndex andType:0];
    [self loadALLSuggestion:beginIndex andEnd:endIndex andType:1];
}

- (void)refreshData {
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    if (_segmentControl.selectedSegmentIndex == 0) {
        //下级公司发布的意见
        beginIndex = 0;
        endIndex = LIST_PAGE_ITEM_COUNTS - 1;
        [self loadALLSuggestion:beginIndex andEnd:endIndex andType:_segmentControl.selectedSegmentIndex];
    }
    else {
        //自己发布的意见
        approvedBegin = 0;
        approvedEnd = LIST_PAGE_ITEM_COUNTS - 1;
        [self loadALLSuggestion:approvedBegin andEnd:approvedEnd andType:_segmentControl.selectedSegmentIndex];
    }
    
}

- (void)loadMoreData {
    if (_segmentControl.selectedSegmentIndex == 0) {
        //下级公司发布的意见
        if (self.dataSourceToMe.count == 0) {
            return;
        }
        // 马上进入刷新状态
        [self.tableView.mj_footer beginRefreshing];
        beginIndex = self.dataSourceToMe.count;
        endIndex = beginIndex + LIST_PAGE_ITEM_COUNTS - 1;
        [self loadALLSuggestion:beginIndex andEnd:endIndex andType:_segmentControl.selectedSegmentIndex];
    }
    else {
        //自己发布的意见
        if (self.dataSourceForMe.count == 0) {
            return;
        }
        // 马上进入刷新状态
        [self.tableView.mj_footer beginRefreshing];
        approvedBegin = self.dataSourceForMe.count;
        approvedEnd = approvedBegin + LIST_PAGE_ITEM_COUNTS - 1;
        [self loadALLSuggestion:approvedBegin andEnd:approvedEnd andType:_segmentControl.selectedSegmentIndex];
    }
}



/**
 *  <#Description#>
 *
 *  @param si   <#si description#>
 *  @param ei   <#ei description#>
 *  @param type 为 1 仅返回自己发布的意见 为 0 返回下级公司发布的意见
 */
- (void)loadALLSuggestion:(NSInteger)si andEnd:(NSInteger)ei andType:(NSInteger)type{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:[NSNumber numberWithInteger:type] forKey:@"os"];
    [param setValue:[NSNumber numberWithInteger:si] forKey:@"si"];
    [param setValue:[NSNumber numberWithInteger:ei] forKey:@"ei"];
    
    
    [HttpClient getWithUrl:HTTP_GET_ALL_SUGGESTION token:[[AccountManager manager]token] paramDic:param resultClass:[SuggestionDataResp class] success:^(SuggestionDataResp *obj) {
        if (si == 0) {
            //下拉刷新
            [self.tableView.mj_header endRefreshing];
            if (type == 0) {
                [self.dataSourceToMe removeAllObjects];
            }
            else {
                [self.dataSourceForMe removeAllObjects];
            }
        }
        else {
            //上拉加载更多
            [self.tableView.mj_footer endRefreshing];
        }
        if (obj.getSuggestionResult != nil && obj.getSuggestionResult.count > 0) {
            if (type == 0) {
                [self.dataSourceToMe addObjectsFromArray:obj.getSuggestionResult];
            }
            else {
                [self.dataSourceForMe addObjectsFromArray:obj.getSuggestionResult];
            }
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        if (si == 0) {
            //下拉刷新
            [self.tableView.mj_header endRefreshing];
            if (type == 0) {
                [self.dataSourceToMe removeAllObjects];
            }
            else {
                [self.dataSourceForMe removeAllObjects];
            }
        }
        else {
            //上拉加载更多
            [self.tableView.mj_footer endRefreshing];
        }
        [self.tableView reloadData];
        CMLog(@"获取子用户数据失败：%@", error);
    }];
}

/**
 *  阅读一条意见
 *
 *  @param suggestionId <#suggestionId description#>
 */
- (void)viewOneSuggestion:(NSString *)suggestionId {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:suggestionId forKey:@"id"];
    [HttpClient getWithUrl:HTTP_GET_VIEW_ONE_SUGGESTION token:[[AccountManager manager]token] paramDic:param resultClass:[SuggestionDataResp class] success:^(SuggestionDataResp *obj) {
        //通知重新获取未读公告条数
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshSuggestionCount" object:nil];
        
    } failure:^(NSError *error) {
        CMLog(@"修改数据失败：%@", error);
    }];
}

/**
 *   删除一条意见
 *
 *  @param suggestionId <#suggestionId description#>
 */
- (void)deleteOneSuggestion:(SuggestionDataResp *)suggestion {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:suggestion.guidId forKey:@"id"];
    HUD  = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.labelText = @"意见删除中...";
    [HttpClient deleteWithUrl:HTTP_DELETE_ONE_SUGGESTION token:[[AccountManager manager]token] paramDic:param resultClass:[SuggestionDataResp class] success:^(SuggestionDataResp *obj) {
        [self.dataSourceForMe removeObject:suggestion];
        [self.tableView reloadData];
        [HUD setHidden:YES];
    } failure:^(NSError *error) {
        CMLog(@"修改数据失败：%@", error);
        [HUD setHidden:YES];
        [Tools showMessageCenter:@"意见删除失败，请重试！"];
    }];
}


#pragma mark - 切换事件
-(void)switchView
{
    [self.tableView reloadData];
    //    if (_segmentControl.selectedSegmentIndex == 0) {
    //        [self.tableView reloadData];
    //    } else if (_segmentControl.selectedSegmentIndex == 1) {
    //
    //    }
}

- (void)addOneSuggestion {
    PublishNoticeViewController *view = [PublishNoticeViewController new];
    view.publishType = KKPublish_Suggestion;
    [self.navigationController pushViewController:view animated:YES];
}

#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_segmentControl.selectedSegmentIndex == 1) {
        return self.dataSourceForMe.count;
    } else if (_segmentControl.selectedSegmentIndex == 0) {
        return self.dataSourceToMe.count;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"SuggestionCell";
    
    
    NoticeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[NoticeTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    SuggestionDataResp *item;
    if (_segmentControl.selectedSegmentIndex == 1) {
        item = [self.dataSourceForMe objectAtIndex:indexPath.row];
        [cell setNewNoticeFlag:NO];
    } else if (_segmentControl.selectedSegmentIndex == 0) {
        item = [self.dataSourceToMe objectAtIndex:indexPath.row];
        [cell setNewNoticeFlag:item.viewed == 1 ? NO : YES];
    }
    [cell setTitle:item.title andDetail:item.content andFrom:item.from andDate:[DateTools getChYearMonthDay:item.time]];
 
    if (_segmentControl.selectedSegmentIndex == 1) {
        //滑动按钮
        cell.rightUtilityButtons = [self rightButtons];
        cell.delegate = self;
        cell.tag = indexPath.row;
    }
    
    return cell;
}

-(NSArray *)rightButtons {
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor redColor] title:@"删除"];
    return rightUtilityButtons;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //反选
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SuggestionDataResp *item;
    if (_segmentControl.selectedSegmentIndex == 1) {
        item = [self.dataSourceForMe objectAtIndex:indexPath.row];
    } else if (_segmentControl.selectedSegmentIndex == 0) {
        item = [self.dataSourceToMe objectAtIndex:indexPath.row];
    }
    
    if (item.viewed == 0 && _segmentControl.selectedSegmentIndex == 0) {
        item.viewed = 1;
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self viewOneSuggestion:item.guidId];
    }
    
    NoticeViewController *view = [NoticeViewController new];
    view.viewType = KKView_Suggestion;
    view.titleStr = item.title;
    NSString *formatTime = [DateTools getChYearMonthDay:item.time];
    view.fromAndDateStr = [NSString stringWithFormat:@"%@  %@", item.from, formatTime];
    view.guidId = item.guidId;
    view.contentStr = item.content;
    [self.navigationController pushViewController:view animated:YES];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"SuggestionCell";

    NoticeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[NoticeTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }

    return [cell getHeight];
}

#pragma mark - 滑动按钮代理协议
/**
 *  右侧滑动按钮点击事件
 *
 *  @param cell  单元cell
 *  @param index 下标
 */
-(void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index{
    switch (index) {
        case 0:{
            SuggestionDataResp *item;
            if (_segmentControl.selectedSegmentIndex == 1) {
                item = [self.dataSourceForMe objectAtIndex:cell.tag];
            } else if (_segmentControl.selectedSegmentIndex == 0) {
                item = [self.dataSourceToMe objectAtIndex:cell.tag];
            }
            [self deleteOneSuggestion:item];
            break;
        }
            
        default:
            break;
    }
    [cell hideUtilityButtonsAnimated:YES];
}


/**
 *  滑动的时候把其他的隐藏掉
 *
 *  @param cell cell
 *
 *  @return 隐藏其他的cell
 */
-(BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell{
    return YES;
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
